import utils from "@common/utils/utils";

export const genPreViewData = hiPrintTemplate => {
	let data = {};
	let json = hiPrintTemplate.getJson() || {};
	if (utils.isNotEmptyList(json.panels)) {
		let printElements = json.panels[0].printElements;
		if (utils.isNotEmptyList(printElements)) {
			printElements.forEach(item => {
				let options = $.extend({}, item.options);
				if (item.printElementType.type !== 'table') {
					if (utils.isNotEmpty(options.field)) {
						if (options.fixedValue === 1) {
							data[options.field] = options.testData;
						} else {
							data[options.field] = '测试数据';
						}
					}
				} else {
					let list = [];
					let itemData = {};
					(options.columns || []).forEach(item => {
						item.forEach(child => {
							if (utils.isNotEmpty(child.field)) {
								itemData[child.field] = '测试数据';
							}
						});
					});
					for (let i = 0; i < 50; i++) {
						list.push($.extend({}, itemData));
					}
					data[options.field] = list;
				}
			});
		}
	}
	return data;
};

export const genInitData = json => {
	let data = {};
	if (utils.isNotEmptyList(json.panels)) {
		let printElements = json.panels[0].printElements;
		if (utils.isNotEmptyList(printElements)) {
			printElements.forEach(item => {
				let options = $.extend({}, item.options);
				if (item.printElementType.type !== 'table') {
					if (utils.isNotEmpty(options.field) && options.fixedValue === 1) {
						data[options.field] = options.testData;
					}
				} else {
					data[options.field] = [];
				}
			});
		}
	}
	return data;
};

const genTableItemData = (options, data) => {
	let itemData = $.extend({}, data);
	(options.columns || []).forEach(item => {
		item.forEach(child => {
			if (utils.isNotEmpty(child.field)) {
				itemData[child.field] = data[child.field];
			} else if (!utils.isNotEmpty(child.field) && utils.isNotEmpty(child.testData)) {
                itemData[child.field] = child.testData;
            }
		});
	});
	return itemData;
};

export const genPrintData = (json, data) => {
	let printData = $.extend({}, data);
	if (utils.isNotEmptyList(json.panels)) {
		let printElements = json.panels[0].printElements;
		if (utils.isNotEmptyList(printElements)) {
			printElements.forEach(item => {
				let options = $.extend({}, item.options);
				if (item.printElementType.type !== 'table') {
					if (utils.isNotEmpty(options.field) && options.fixedValue === 1) {
						printData[options.field] = options.testData;
					} else if (utils.isEmpty(options.field) && utils.isNotEmpty(options.testData)) {
                        printData[options.field] = options.testData;
                    } else {
						printData[options.field] = data[options.field];
					}
				} else {
					printData[options.field] = (data[options.field] || []).map(child => genTableItemData(options, child));
				}
			});
		}
	}
	return printData;
};
